package com.example.smartf.service.impl;

import com.example.smartf.model.mongo.User;
import com.example.smartf.model.mysql.Userinfo;
import com.example.smartf.repository.mongoDB.MongoUserUtil;
import com.example.smartf.repository.mysql.UserinfoRepository;
import com.example.smartf.service.UserService;
import com.example.smartf.tool.RedisUtils;
import com.example.smartf.tool.UID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class UserServiceImpl implements UserService {
    //日志记录器
    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private UserinfoRepository userinfoRepository;

    @Autowired
    private MongoUserUtil mongoUserUtil;

    //redis操作  工具类
    @Resource
    private RedisUtils redisUtils = RedisUtils.getInstance();

    @Autowired
    private JavaMailSender mailSender;

    @Value("1033457564@qq.com")
    private String from;

    public void sendMail(String title,String content,String email){
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setSubject(title);
        message.setTo(email);
        message.setText(content);
        mailSender.send(message);
    }

    //注册时发送验证码
    @Override
    public String regsendCode(String username){
        if( null != userinfoRepository.findByUsername(username)){
            logger.info("注册：" + username + " 已存在！");
            return "has";
        }else {

            //生成随机验证码
            String code = UID.getUid().substring(0, 4);
            //向邮箱发送验证码
            new Thread(new Runnable() {
                @Override
                public void run() {
                    sendMail("欢迎注册智慧种植系统", "验证码："+code, username);
                    logger.info("注册-发送验证码：" + username + " 发送成功！");
                    //redis存入验证码，等待验证
                    redisUtils.set(username, code);
                    //设置超时时间为 60s
                    redisUtils.expire(username, 60);
                }
            }).start();

            return "success";
        }
    }


    //用户注册
    @Override
    public String addUser(String username,String password,String code){
        if( null != userinfoRepository.findByUsername(username)){
            logger.info("注册：" + username + " 已存在！");
            return "has";
        }else{
            if( null != code && redisUtils.hasKey(username) == true && code.equals(redisUtils.get(username)) == true){
                userinfoRepository.save(new Userinfo(username,password));
                mongoUserUtil.addUser(new User(username,new String[0]));
                logger.info("注册：" + username + " 注册成功！");
                redisUtils.delete(username);
                return "success";
            }
            return "code error";
        }
    }

    //用户登录
    @Override
    public String login(String username,String password){
        if( null == userinfoRepository.findByUsername(username)){
            logger.info("登录：" + username + " 用户不存在！");
            return "not exist";
        }
        if( password != null && password.equals(userinfoRepository.findByUsername(username).getPassword()) == true){

            if( "root".equals(userinfoRepository.findByUsername(username).getPermission() )){
                logger.info("Root用户登录：" + username + " 登录成功！");
                return "root";
            }else {
                logger.info("登录：" + username + " 登录成功！");
                return "success";
            }
        }else{
            logger.info("登录：" + username + " 密码错误！");
            return "password error";
        }
    }

    //忘记密码时 发送验证码
    public String resetpwdsendCode(String username){
        if( null == userinfoRepository.findByUsername(username)){
            logger.info("忘记密码-验证码：" + username + " 不已存在！");
            return "not exist";
        }else {

            //生成随机验证码
            String code = UID.getUid().substring(0, 4);
            //向邮箱发送验证码
            new Thread(new Runnable() {
                @Override
                public void run() {
                    sendMail("智慧种植系统-忘记密码", "验证码："+code, username);
                    logger.info("忘记密码-发送验证码：" + username + " 发送成功！");
                    //redis存入验证码，等待验证
                    redisUtils.set(username, code);
                    //设置超时时间为 60s
                    redisUtils.expire(username, 60);
                }
            }).start();

            return "success";
        }
    }


    //忘记密码---用户名，新密码，验证码
    public String resetpwd(String username,String newpassword,String code){
        //用户名不存在
        if( null == userinfoRepository.findByUsername(username)){
            logger.info("忘记密码：" + username + " 不已存在！");
            return "not exist";
        }else {
            //判断验证码
            if( code != null && redisUtils.hasKey(username) == true && code.equals(redisUtils.get(username)) == true){
                int result = userinfoRepository.resetPassword(username,newpassword);
                //是否修改成功
                if(result != 0){
                    redisUtils.delete(username);
                    return "success";
                }else{
                    return "error";
                }

            }else{
                return "code error";
            }

        }
    }
}
